<template>
  <div class="flow-container">
    <!-- 背景装饰 -->
    <div class="bg-decoration">
      <div class="floating-icon icon-1"><el-icon><Reading /></el-icon></div>
      <div class="floating-icon icon-2"><el-icon><Star /></el-icon></div>
      <div class="floating-icon icon-3"><el-icon><ChatDotRound /></el-icon></div>
      <div class="floating-icon icon-4"><el-icon><Trophy /></el-icon></div>
      <div class="floating-icon icon-5"><el-icon><Star /></el-icon></div>
    </div>
    
    <div class="user-profile-layout" v-loading="loading">
      <!-- 左侧：tab切换和帖子/资料内容 -->
      <div class="user-profile-main">
        <div class="content-header">
          <h2 class="page-title">
            <el-icon class="title-icon"><User /></el-icon>
            用户动态
          </h2>
        </div>
        <el-tabs v-model="activeTab" class="custom-tabs">
          <el-tab-pane name="recent">
            <template #label>
              <span class="tab-label">
                <el-icon class="tab-icon"><Timer /></el-icon>
                最近
              </span>
            </template>
            <div class="post-list">
              <div v-if="recentPosts.length" class="posts-container">
                <div v-for="post in recentPosts" :key="post.id" class="post-item" @click="goToPost(post.id)">
                  <div class="post-item-layout">
                    <div class="post-icon"><el-icon><Document /></el-icon></div>
                    <div class="post-content-wrapper">
                      <h4 class="post-title">{{ post.title }}</h4>
                      <p class="post-content">{{ truncateContent(post.content) }}</p>
                      <div class="post-meta">
                        <span class="meta-item">
                          <el-icon class="meta-icon"><User /></el-icon>
                          {{ user.nickname }}
                        </span>
                        <span class="meta-item">
                          <el-icon class="meta-icon"><Folder /></el-icon>
                          {{ post.categoryName || '未分类' }}
                        </span>
                        <span class="meta-item">
                          <el-icon class="meta-icon"><Clock /></el-icon>
                          {{ post.time || '--' }}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="empty-state">
                <div class="empty-icon"><el-icon><Notification /></el-icon></div>
                <div class="empty-text">暂无内容</div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane name="posts">
            <template #label>
              <span class="tab-label">
                <el-icon class="tab-icon"><Document /></el-icon>
                帖子
              </span>
            </template>
            <div class="post-list">
              <div v-if="userPosts.length" class="posts-container">
                <div v-for="post in userPosts" :key="post.id" class="post-item" @click="goToPost(post.id)">
                  <div class="post-item-layout">
                    <div class="post-icon"><el-icon><Document /></el-icon></div>
                    <div class="post-content-wrapper">
                      <h4 class="post-title">{{ post.title }}</h4>
                      <p class="post-content">{{ truncateContent(post.content) }}</p>
                      <div class="post-meta">
                        <span class="meta-item">
                          <el-icon class="meta-icon"><User /></el-icon>
                          {{ user.nickname }}
                        </span>
                        <span class="meta-item">
                          <el-icon class="meta-icon"><Folder /></el-icon>
                          {{ post.categoryName || '未分类' }}
                        </span>
                        <span class="meta-item">
                          <el-icon class="meta-icon"><Clock /></el-icon>
                          {{ post.time || '--' }}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="empty-state">
                <div class="empty-icon"><el-icon><DocumentCopy /></el-icon></div>
                <div class="empty-text">暂无帖子</div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane name="info">
            <template #label>
              <span class="tab-label">
                <el-icon class="tab-icon"><Files /></el-icon>
                资料
              </span>
            </template>
            <div class="post-list">
              <div v-if="userResources.length" class="posts-container">
                <div v-for="res in userResources" :key="res.id" class="post-item resource-item">
                  <div class="post-item-layout">
                    <div class="post-icon"><el-icon><Ticket /></el-icon></div>
                    <div class="post-content-wrapper">
                      <h4 class="post-title">{{ res.title }}</h4>
                      <p class="post-content">{{ res.content || '...' }}</p>
                      <div class="post-meta resource-meta">
                        <span class="meta-item">
                          <el-icon class="meta-icon"><User /></el-icon>
                          {{ user.nickname }}
                        </span>
                        <span v-if="res.fileName" class="meta-item">
                          <el-icon class="meta-icon"><Paperclip /></el-icon>
                          {{ res.fileName }}
                        </span>
                        <span v-if="res.fileType" class="meta-item">
                          <el-icon class="meta-icon"><PriceTag /></el-icon>
                          {{ res.fileType }}
                        </span>
                        <span class="meta-item">
                          <el-icon class="meta-icon"><Clock /></el-icon>
                          {{ res.time || '--' }}
                        </span>
                      </div>
                    </div>
                    <div class="resource-actions" @click.stop>
                      <el-button
                        :class="['like-btn', { liked: res.isLiked }]"
                        @click="toggleLike(res, $event)"
                        size="small"
                      >
                        <span v-html="res.isLiked ? likeSvgPurple : likeSvgGray" style="vertical-align: middle;"></span>
                        <span style="margin-left: 6px;">{{ res.likes || 0 }}</span>
                      </el-button>
                      <el-button @click="downloadResourceFile(res, $event)" size="small" class="download-btn">
                        <el-icon class="download-icon"><Download /></el-icon>
                        下载
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="empty-state">
                <div class="empty-icon"><el-icon><FolderOpened /></el-icon></div>
                <div class="empty-text">暂无学习资料</div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- 右侧：用户信息 -->
      <div class="user-profile-info">
        <div class="profile-card">
          <div class="avatar-container">
            <img :src="user.avatar" class="profile-avatar" />
            <div class="avatar-glow"></div>
          </div>
          <div class="profile-nick-row">
            <div class="profile-nick">
              <el-icon class="nickname-icon"><Star /></el-icon>
              {{ user.nickname }}
            </div>
            <el-button 
              v-if="showFollowButton"
              size="small" 
              type="primary" 
              @click="toggleFollow" 
              :loading="followLoading"
              :plain="!isFollowed" 
              class="follow-btn"
            >
              <el-icon class="follow-icon">
                <Check v-if="isFollowed" />
                <Plus v-else />
              </el-icon>
              {{ isFollowed ? '已关注' : '关注' }}
            </el-button>
          </div>
          <div class="profile-stats">
            <div class="stat-item">
              <el-icon class="stat-icon"><Document /></el-icon>
              <span class="stat-label">发帖数</span>
              <span class="stat-value">{{ user.postCount }}</span>
            </div>
          </div>
          <div class="profile-bio">
            <el-icon class="bio-icon"><ChatDotRound /></el-icon>
            {{ user.bio }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  User, 
  Document, 
  Folder, 
  Clock, 
  Star, 
  Reading, 
  Ticket, 
  Files, 
  Download, 
  ChatDotRound, 
  Trophy,
  Timer,
  Plus,
  Check,
  Connection,
  Paperclip,
  PriceTag,
  UserFilled,
  DocumentCopy,
  FolderOpened,
  Notification
} from '@element-plus/icons-vue'
import { getUserByIdApi, getUserPostsApi, getUserResourcesApi } from '../../api/user'
import { likePost, unlikePost, hasLiked } from '../../api/post'
import { likeResource, unlikeResource, hasLikedResource, downloadResource } from '../../api/resources'
import { useUserStore } from '../../stores/user'
import { checkFollowStatus, followUser, unfollowUser } from '../../api/follow'

// 点赞SVG
const likeSvgGray = `<svg t="1751619712990" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6069" width="22" height="22"><path d="M939.358251 423.424662c-23.01825-37.252439-62.924121-60.779272-107.019409-63.209624-2.755764-0.38681-5.510504-0.579191-8.347109-0.579191l-152.202471-0.121773c6.649444-28.975938 10.015098-58.653865 10.015098-88.657202 0-28.223808-3.213181-57.139372-9.556657-85.952604-0.447185-2.043542-1.098008-4.006244-1.932002-5.866614-15.820314-57.302077-67.37755-96.841605-127.282918-96.841605-72.827679 0-132.081201 59.254545-132.081201 132.081201 0 3.334955 0.132006 6.66991 0.406253 10.015098-2.196015 57.211003-32.108279 109.947088-80.269162 141.363611-14.447037 9.42465-18.524912 28.773324-9.099239 43.220361 9.414417 14.437827 28.752858 18.535145 43.220361 9.099239 65.811892-42.925648 106.429984-115.325585 108.656699-193.684234 0.030699-1.332345-0.010233-2.663666-0.14224-3.996011-0.203638-2.012843-0.304945-4.016477-0.304945-6.019087 0-38.381146 31.233352-69.614497 69.614497-69.614497 32.57593 0 60.474326 22.204721 67.824735 53.997821 0.356111 1.534959 0.823761 3.019777 1.402953 4.453429 4.696975 22.814612 7.076162 45.579081 7.076162 67.743894 0 37.485753-6.222725 74.352405-18.494213 109.592001-3.324722 9.546424-1.819438 20.111037 4.02671 28.345582 5.856381 8.245801 15.332197 13.146415 25.448602 13.156648l193.226816 0.101307c1.423419 0.264013 2.857071 0.426719 4.300956 0.477884 24.116257 0.9967 45.935192 13.614066 58.603723 34.090423 7.838525 12.31242 11.438517 26.800389 10.431583 41.939181-0.080841 0.945535-0.121773 1.911536-0.11154 2.877537 0 0.854461 0.040932 1.697665 0.11154 2.53166 0.010233 0.335644-0.030699 0.661056-0.11154 0.976234-0.101307 0.376577-0.193405 0.772596-0.284479 1.159406l-74.972529 330.391802c-0.914836 1.281179-1.738597 2.6432-2.449795 4.046153-5.937223 11.762905-14.660908 21.48329-25.346271 28.172643-10.746762 6.812149-23.059182 10.614755-35.757388 11.06194-0.854461-0.061398-513.766226-0.224104-513.766226-0.224104-0.467651-0.020466-0.935302-0.030699-1.402953-0.030699 0 0-111.01542 0.172939-112.718201 0.457418-1.932002 0-3.446495-1.50426-3.446495-3.415796l0.299829-416.334173c0-1.901303 1.545192-3.446495 3.01466-3.456728l1.245364 0.121773c1.174756 0.132006 2.653433 0.284479 3.52836 0.193405l83.82822-0.222057 0 339.367221c0 17.253966 13.979386 31.233352 31.233352 31.233352s31.233352-13.979386 31.233352-31.233352L281.009092 435.350273c0-1.778506 0-8.631588 0-10.411117 0-17.253966-13.979386-30.928407-31.233352-30.928407-1.50426 0-117.547183 0.304945-119.402437 0.304945-36.34272 0-65.913199 29.566386-65.913199 65.893756l-0.299829 416.334173c0 36.337603 29.571503 65.902966 65.913199 65.902966 2.541893 0 111.406323-0.457418 111.406323-0.457418 0.457418 0.020466 0.925069 0.030699 1.382487 0.030699 0 0 511.458671 0.274246 512.505513 0.274246 25.469068 0 50.296523-7.197936 71.647807-20.73116 19.612687-12.281721 35.777855-29.881564 46.839795-50.967812 3.660366-5.622044 6.435573-11.875468 8.256034-18.615986 0.11154-0.416486 0.213871-0.823761 0.304945-1.240247l74.881454-330.340637c1.596358-6.212492 2.257413-12.586666 2.00261-18.992563C960.892707 473.366098 953.948551 446.331371 939.358251 423.424662z" fill="#8a8a8a" p-id="6070"></path><path d="M450.027553 518.650467c-17.253966 0-31.233352 13.979386-31.233352 31.233352l0 30.470989c0 17.253966 13.979386 31.233352 31.233352 31.233352 17.253966 0 31.233352-13.979386 31.233352-31.233352l0-30.470989C481.260905 532.629853 467.281519 518.650467 450.027553 518.650467z" fill="#8a8a8a" p-id="6071"></path><path d="M693.805696 518.650467c-17.253966 0-31.233352 13.979386-31.233352 31.233352l0 30.470989c0 17.253966 13.979386 31.233352 31.233352 31.233352 17.253966 0 31.233352-13.979386 31.233352-31.233352l0-30.470989C725.039048 532.629853 711.058638 518.650467 693.805696 518.650467z" fill="#8a8a8a" p-id="6072"></path><path d="M648.940882 660.09492c-14.304797-9.393951-33.592073-5.398964-43.159986 8.763594-0.132006 0.193405-13.614066 19.754926-34.171264 19.754926-19.98824 0-32.423457-18.09717-33.266661-19.368116-9.17087-14.427594-28.254507-18.809391-42.834574-9.770528-14.650675 9.109472-19.155269 28.366048-10.055007 43.016723 11.214413 18.047028 41.96988 48.588625 86.156242 48.588625 43.962258 0 75.104535-30.318516 86.572728-48.222281C667.404396 688.461991 663.216004 669.500127 648.940882 660.09492z" fill="#8a8a8a" p-id="6073"></path></svg>`
const likeSvgPurple = `<svg t="1751619712990" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6069" width="22" height="22"><path d="M939.358251 423.424662c-23.01825-37.252439-62.924121-60.779272-107.019409-63.209624-2.755764-0.38681-5.510504-0.579191-8.347109-0.579191l-152.202471-0.121773c6.649444-28.975938 10.015098-58.653865 10.015098-88.657202 0-28.223808-3.213181-57.139372-9.556657-85.952604-0.447185-2.043542-1.098008-4.006244-1.932002-5.866614-15.820314-57.302077-67.37755-96.841605-127.282918-96.841605-72.827679 0-132.081201 59.254545-132.081201 132.081201 0 3.334955 0.132006 6.66991 0.406253 10.015098-2.196015 57.211003-32.108279 109.947088-80.269162 141.363611-14.447037 9.42465-18.524912 28.773324-9.099239 43.220361 9.414417 14.437827 28.752858 18.535145 43.220361 9.099239 65.811892-42.925648 106.429984-115.325585 108.656699-193.684234 0.030699-1.332345-0.010233-2.663666-0.14224-3.996011-0.203638-2.012843-0.304945-4.016477-0.304945-6.019087 0-38.381146 31.233352-69.614497 69.614497-69.614497 32.57593 0 60.474326 22.204721 67.824735 53.997821 0.356111 1.534959 0.823761 3.019777 1.402953 4.453429 4.696975 22.814612 7.076162 45.579081 7.076162 67.743894 0 37.485753-6.222725 74.352405-18.494213 109.592001-3.324722 9.546424-1.819438 20.111037 4.02671 28.345582 5.856381 8.245801 15.332197 13.146415 25.448602 13.156648l193.226816 0.101307c1.423419 0.264013 2.857071 0.426719 4.300956 0.477884 24.116257 0.9967 45.935192 13.614066 58.603723 34.090423 7.838525 12.31242 11.438517 26.800389 10.431583 41.939181-0.080841 0.945535-0.121773 1.911536-0.11154 2.877537 0 0.854461 0.040932 1.697665 0.11154 2.53166 0.010233 0.335644-0.030699 0.661056-0.11154 0.976234-0.101307 0.376577-0.193405 0.772596-0.284479 1.159406l-74.972529 330.391802c-0.914836 1.281179-1.738597 2.6432-2.449795 4.046153-5.937223 11.762905-14.660908 21.48329-25.346271 28.172643-10.746762 6.812149-23.059182 10.614755-35.757388 11.06194-0.854461-0.061398-513.766226-0.224104-513.766226-0.224104-0.467651-0.020466-0.935302-0.030699-1.402953-0.030699 0 0-111.01542 0.172939-112.718201 0.457418-1.932002 0-3.446495-1.50426-3.446495-3.415796l0.299829-416.334173c0-1.901303 1.545192-3.446495 3.01466-3.456728l1.245364 0.121773c1.174756 0.132006 2.653433 0.284479 3.52836 0.193405l83.82822-0.222057 0 339.367221c0 17.253966 13.979386 31.233352 31.233352 31.233352s31.233352-13.979386 31.233352-31.233352L281.009092 435.350273c0-1.778506 0-8.631588 0-10.411117 0-17.253966-13.979386-30.928407-31.233352-30.928407-1.50426 0-117.547183 0.304945-119.402437 0.304945-36.34272 0-65.913199 29.566386-65.913199 65.893756l-0.299829 416.334173c0 36.337603 29.571503 65.902966 65.913199 65.902966 2.541893 0 111.406323-0.457418 111.406323-0.457418 0.457418 0.020466 0.925069 0.030699 1.382487 0.030699 0 0 511.458671 0.274246 512.505513 0.274246 25.469068 0 50.296523-7.197936 71.647807-20.73116 19.612687-12.281721 35.777855-29.881564 46.839795-50.967812 3.660366-5.622044 6.435573-11.875468 8.256034-18.615986 0.11154-0.416486 0.213871-0.823761 0.304945-1.240247l74.881454-330.340637c1.596358-6.212492 2.257413-12.586666 2.00261-18.992563C960.892707 473.366098 953.948551 446.331371 939.358251 423.424662z" fill="#854efc" p-id="6070"></path><path d="M450.027553 518.650467c-17.253966 0-31.233352 13.979386-31.233352 31.233352l0 30.470989c0 17.253966 13.979386 31.233352 31.233352 31.233352 17.253966 0 31.233352-13.979386 31.233352-31.233352l0-30.470989C481.260905 532.629853 467.281519 518.650467 450.027553 518.650467z" fill="#854efc" p-id="6071"></path><path d="M693.805696 518.650467c-17.253966 0-31.233352 13.979386-31.233352 31.233352l0 30.470989c0 17.253966 13.979386 31.233352 31.233352 31.233352 17.253966 0 31.233352-13.979386 31.233352-31.233352l0-30.470989C725.039048 532.629853 711.058638 518.650467 693.805696 518.650467z" fill="#854efc" p-id="6072"></path><path d="M648.940882 660.09492c-14.304797-9.393951-33.592073-5.398964-43.159986 8.763594-0.132006 0.193405-13.614066 19.754926-34.171264 19.754926-19.98824 0-32.423457-18.09717-33.266661-19.368116-9.17087-14.427594-28.254507-18.809391-42.834574-9.770528-14.650675 9.109472-19.155269 28.366048-10.055007 43.016723 11.214413 18.047028 41.96988 48.588625 86.156242 48.588625 43.962258 0 75.104535-30.318516 86.572728-48.222281C667.404396 688.461991 663.216004 669.500127 648.940882 660.09492z" fill="#854efc" p-id="6073"></path></svg>`

const route = useRoute()
const router = useRouter()
const userId = route.params.userId as string
const activeTab = ref('recent')
const loading = ref(false)

// 用户信息
const user = ref({
  id: '',
  avatar: '',
  nickname: '',
  postCount: 0,
  fansCount: 0,
  bio: '',
  gender: '',
  birthday: '',
  email: ''
})

// 帖子和资源数据
const recentPosts = ref<any[]>([])
const userPosts = ref<any[]>([])
const userResources = ref<any[]>([])

const isFollowed = ref(false)
const followLoading = ref(false)

async function toggleFollow() {
  const userStore = useUserStore()
  const currentUserId = Number(userStore.id)
  const targetUserId = Number(userId)
  
  if (!currentUserId) {
    ElMessage.error('请先登录')
    return
  }
  
  if (currentUserId === targetUserId) {
    ElMessage.info('不能关注自己')
    return
  }
  
  followLoading.value = true
  
  try {
    if (isFollowed.value) {
      // 取消关注
      const res = await unfollowUser(currentUserId, targetUserId)
      if (res.code === 200) {
        isFollowed.value = false
        ElMessage.success('取消关注成功！')
        // 更新粉丝数
        if (user.value.fansCount > 0) {
          user.value.fansCount--
        }
      } else {
        ElMessage.error(res.data?.message || '取消关注失败')
      }
    } else {
      // 关注用户
      const res = await followUser(currentUserId, targetUserId)
      if (res.code === 200) {
        isFollowed.value = true
        ElMessage.success('关注成功！')
        // 更新粉丝数
        user.value.fansCount++
      } else {
        ElMessage.error(res.data?.message || '关注失败')
      }
    }
  } catch (error) {
    console.error('关注操作失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    followLoading.value = false
  }
}

// 跳转到帖子详情页
function goToPost(postId: number) {
  router.push(`/forum/${postId}`)
}

// 检查关注状态
async function checkFollow() {
  const userStore = useUserStore()
  const currentUserId = Number(userStore.id)
  const targetUserId = Number(userId)
  
  if (!currentUserId || currentUserId === targetUserId) {
    return
  }
  
  try {
    const res = await checkFollowStatus(currentUserId, targetUserId)
    if (res.code === 200) {
      isFollowed.value = res.data || false
    }
  } catch (error) {
    console.error('检查关注状态失败:', error)
  }
}

// 获取用户信息
async function fetchUserInfo() {
  try {
    const res: any = await getUserByIdApi(userId)
    if (res.data && res.code === 200) {
      user.value = {
        id: res.data.id || '',
        avatar: res.data.avatar || 'https://classtopia-avatar.oss-cn-wuhan-lr.aliyuncs.com/903c92f279a11371074498d20e48c267.jpg',
        nickname: res.data.nickname || '匿名用户',
        postCount: 0, // 将在获取帖子时更新
        fansCount: 0, // 暂时保留mock数据
        bio: res.data.personalIntroduce || '这个用户很懒，什么都没有留下~',
        gender: res.data.gender || '',
        birthday: res.data.birthday || '',
        email: res.data.email || ''
      }
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 获取用户帖子
async function fetchUserPosts() {
  try {
    const res: any = await getUserPostsApi(userId, 1, 50) // 获取前50个帖子
    if (res.code === 200 && res.data) {
      const posts = res.data.records || []
      userPosts.value = posts.map((post: any) => ({
        id: post.id,
        title: post.title,
        content: post.content || '',
        likes: post.likeCount || 0,
        isLiked: post.isLiked || false,
        time: formatTime(post.createTime) || '--',
        categoryName: post.categoryName || '未分类'
      }))
      // 更新帖子数量
      user.value.postCount = res.data.total || posts.length
      // 取最近的几个帖子作为recent
      recentPosts.value = userPosts.value.slice(0, 5)
    }
  } catch (error) {
    console.error('获取用户帖子失败:', error)
    ElMessage.error('获取用户帖子失败')
  }
}

// 获取用户资源
async function fetchUserResources() {
  try {
    const res: any = await getUserResourcesApi(userId, 1, 20) // 获取前20个资源
    if (res.code === 200) {
      const resources = res.data.records || []
      userResources.value = resources.map((resource: any) => ({
        id: resource.id,
        title: resource.title || resource.fileName || '未命名资源',
        content: resource.description || '',
        likes: resource.likeCount || 0, // 资源点赞数
        time: formatTime(resource.createdAt) || '--',
        fileName: resource.fileName,
        fileType: resource.fileType
      }))
    }
  } catch (error) {
    console.error('获取用户资源失败:', error)
    ElMessage.error('获取用户资源失败')
  }
}

// 格式化时间
function formatTime(timeStr: string) {
  if (!timeStr) return '--'
  try {
    const date = new Date(timeStr)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit', 
      day: '2-digit'
    })
  } catch (error) {
    return '--'
  }
}

// 初始化数据
async function initData() {
  if (!userId) {
    ElMessage.error('用户ID不能为空')
    return
  }
  
  loading.value = true
  try {
    await Promise.all([
      fetchUserInfo(),
      fetchUserPosts(),
      fetchUserResources(),
      checkFollow() // 添加检查关注状态
    ])
  } finally {
    loading.value = false
  }
}

const userStore = useUserStore()

// 计算属性：是否显示关注按钮（不能关注自己）
const showFollowButton = computed(() => {
  const currentUserId = Number(userStore.id)
  const targetUserId = Number(userId)
  return currentUserId && currentUserId !== targetUserId
})

const resourceDownloadLoading = ref<{[key:number]: boolean}>({})
const toggleLike = async (item: any, e: Event) => {
  e.stopPropagation && e.stopPropagation()
  const uid = Number(userStore.id || user.value.id)
  if (item.isLiked) {
    const res = await unlikeResource(item.id, uid)
    if (res.data && res.data.code === 200) {
      item.isLiked = false
      item.likes = (item.likes || 1) - 1
      ElMessage.success('取消点赞成功')
    } else {
      ElMessage.error(res.data?.message || '取消点赞失败')
    }
  } else {
    const hasLikeRes = await hasLikedResource(item.id, uid)
    console.log('hasLikeRes:', hasLikeRes)
    if (hasLikeRes.data && (hasLikeRes.data.code === 0 || hasLikeRes.data.code === 200)) {
      ElMessage.info('已经点过赞了')
      item.isLiked = true
      return
    }
    const res = await likeResource(item.id, uid)
    if (res.data && res.data.code === 200) {
      item.isLiked = true
      item.likes = (item.likes || 0) + 1
      ElMessage.success('点赞成功')
    } else {
      ElMessage.error(res.data?.message || '点赞失败')
    }
  }
}

function downloadResourceFile(res: any, e: Event) {
  e.stopPropagation && e.stopPropagation()
  const uid = Number(userStore.id || user.value.id)
  if (resourceDownloadLoading.value[res.id]) return
  resourceDownloadLoading.value[res.id] = true
  res.downloadCount = (res.downloadCount || 0) + 1
  downloadResource(res.id, uid).then(r => {
    // 调试输出，便于排查 fileUrl 问题
    console.log('下载资源参数:', res)
    console.log('下载接口返回:', r)
    if (r.data && r.data.fileUrl) {
      window.open(r.data.fileUrl, '_blank')
    } else {
      res.downloadCount = (res.downloadCount || 1) - 1
      ElMessage.error(r.data?.message || '下载失败，未获取到文件地址')
    }
  }).catch(err => {
    res.downloadCount = (res.downloadCount || 1) - 1
    ElMessage.error(err.message || '下载失败')
  }).finally(() => {
    resourceDownloadLoading.value[res.id] = false
  })
}

onMounted(() => {
  initData()
})

function truncateContent(content: string) {
  if (!content) return '...';
  return content.length > 15 ? content.slice(0, 15) + '...' : content;
}
</script>

<style scoped>
/* 背景装饰 */
.bg-decoration {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: -1;
  overflow: hidden;
}

.floating-icon {
  position: absolute;
  font-size: 24px;
  opacity: 0.1;
  animation: float 6s ease-in-out infinite;
  color: var(--primary-purple);
}

.icon-1 {
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.icon-2 {
  top: 20%;
  right: 15%;
  animation-delay: -2s;
}

.icon-3 {
  bottom: 30%;
  left: 8%;
  animation-delay: -4s;
}

.icon-4 {
  bottom: 20%;
  right: 20%;
  animation-delay: -1s;
}

.icon-5 {
  top: 50%;
  left: 50%;
  animation-delay: -3s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
    opacity: 0.1;
  }
  25% {
    transform: translateY(-20px) rotate(5deg);
    opacity: 0.15;
  }
  50% {
    transform: translateY(-10px) rotate(-5deg);
    opacity: 0.1;
  }
  75% {
    transform: translateY(-15px) rotate(3deg);
    opacity: 0.12;
  }
}

/* 主布局 */
.user-profile-layout {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  width: 1300px;
  margin: 20px auto;
  position: relative;
  animation: slideIn 0.8s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.content-header {
  margin-bottom: 24px;
  padding: 0 8px;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 28px;
  font-weight: bold;
  color: var(--primary-blue);
  margin: 0;
  gap: 12px;
}

.title-icon {
  font-size: 32px;
  animation: bounce 2s infinite;
  color: var(--primary-blue);
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

/* 自定义标签页 */
.custom-tabs {
  --el-tabs-header-height: 60px;
}

.custom-tabs :deep(.el-tabs__header) {
  margin-bottom: 20px;
  border-bottom: 2px solid var(--light-purple);
}

.custom-tabs :deep(.el-tabs__nav-wrap) {
  padding: 0 16px;
}

.custom-tabs :deep(.el-tabs__item) {
  height: 60px;
  line-height: 60px;
  font-size: 16px;
  font-weight: 500;
  color: var(--text-secondary);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 12px 12px 0 0;
  margin-right: 8px;
  padding: 0 24px;
}

.custom-tabs :deep(.el-tabs__item:hover) {
  color: var(--primary-purple);
  background: var(--light-purple);
  transform: translateY(-2px);
}

.custom-tabs :deep(.el-tabs__item.is-active) {
  color: var(--primary-purple);
  background: linear-gradient(135deg, var(--light-purple), var(--light-blue));
  font-weight: bold;
}

.custom-tabs :deep(.el-tabs__active-bar) {
  background: linear-gradient(90deg, var(--primary-purple), var(--primary-blue));
  height: 3px;
  border-radius: 2px;
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tab-icon {
  font-size: 18px;
  transition: transform 0.3s ease;
  color: var(--primary-purple);
}

.custom-tabs :deep(.el-tabs__item:hover) .tab-icon {
  transform: scale(1.2) rotate(10deg);
}

.user-profile-main {
  flex: 3;
  background: var(--bg-primary);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--border-light);
  padding: 36px 48px 24px 48px;
  margin-right: 32px;
}

/* 用户信息卡片 */
.user-profile-info {
  flex: 1;
  min-width: 220px;
  max-width: 320px;
  position: sticky;
  top: 20px;
  animation: slideInRight 0.8s ease-out 0.2s both;
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.profile-card {
  background: var(--bg-primary);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--border-light);
  padding: 36px 32px 24px 32px;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.profile-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, var(--light-blue), var(--primary-blue), var(--light-blue));
  background-size: 200% 100%;
  animation: shimmer 3s ease-in-out infinite;
}

.profile-card:hover {
  border-color: var(--light-blue);
  box-shadow: var(--shadow-blue);
  transform: translateY(-4px);
}

.avatar-container {
  position: relative;
  margin-bottom: 20px;
}

.profile-avatar {
  width: 90px;
  height: 90px;
  border-radius: 50%;
  border: 4px solid var(--light-purple);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  z-index: 2;
}

.avatar-glow {
  position: absolute;
  top: -4px;
  left: -4px;
  width: 98px;
  height: 98px;
  border-radius: 50%;
  background: linear-gradient(45deg, var(--primary-purple), var(--primary-blue));
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 1;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
    opacity: 0.3;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.6;
  }
}

.profile-card:hover .avatar-glow {
  opacity: 0.5;
}

.profile-card:hover .profile-avatar {
  transform: scale(1.1);
  border-color: var(--primary-purple);
}

.profile-nick-row {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  gap: 12px;
  flex-wrap: wrap;
  justify-content: center;
}

.profile-nick {
  font-size: 22px;
  font-weight: bold;
  color: var(--primary-blue);
  display: flex;
  align-items: center;
  gap: 8px;
}

.nickname-icon {
  font-size: 20px;
  animation: sparkle 2s infinite;
  color: var(--primary-purple);
}

@keyframes sparkle {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.2);
  }
}

.follow-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s ease;
}

.follow-btn:hover {
  transform: scale(1.05);
}

.follow-icon {
  font-size: 14px;
  transition: transform 0.3s ease;
  color: inherit;
}

.follow-btn:hover .follow-icon {
  transform: rotate(360deg);
}

.profile-stats {
  margin-bottom: 16px;
  width: 100%;
}

.stat-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px;
  background: var(--light-purple);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-light);
  transition: all 0.3s ease;
}

.stat-item:hover {
  background: var(--primary-purple);
  color: white;
  transform: scale(1.02);
}

.stat-icon {
  font-size: 18px;
  color: var(--primary-blue);
}

.stat-label {
  font-size: 14px;
  color: var(--text-muted);
}

.stat-item:hover .stat-label {
  color: rgba(255, 255, 255, 0.9);
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  color: var(--primary-blue);
}

.stat-item:hover .stat-value {
  color: white;
}

.profile-bio {
  color: var(--text-secondary);
  font-size: 16px;
  text-align: center;
  line-height: 1.5;
  padding: 16px;
  background: var(--bg-secondary);
  border-radius: var(--radius-md);
  border: 1px dashed var(--border-medium);
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.bio-icon {
  font-size: 18px;
  flex-shrink: 0;
  margin-top: 2px;
  color: var(--primary-purple);
}

/* 帖子列表 */
.posts-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.post-item {
  background: var(--bg-primary);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-light);
  padding: 24px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  position: relative;
  overflow: hidden;
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.post-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(180deg, var(--primary-purple), var(--primary-blue));
  transform: scaleY(0);
  transition: transform 0.3s ease;
}

.post-item:hover::before {
  transform: scaleY(1);
}

.post-item:hover {
  box-shadow: var(--shadow-lg);
  background: var(--bg-secondary);
  transform: translateY(-6px) translateX(8px);
  border-color: var(--light-purple);
}

.post-item:active {
  transform: scale(0.98);
}

.post-item-layout {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.post-icon {
  flex-shrink: 0;
  font-size: 32px;
  padding: 18px;
  background: linear-gradient(135deg, #a259ec 0%, #6a82fb 100%);
  border-radius: 50%;
  box-shadow: 0 4px 16px 0 rgba(162, 89, 236, 0.15), 0 1.5px 6px 0 rgba(106, 130, 251, 0.10);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3px solid #fff;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s;
  position: relative;
  z-index: 1;
}

.post-item:hover .post-icon {
  background: linear-gradient(135deg, #6a82fb 0%, #a259ec 100%);
  color: #fff;
  transform: scale(1.15) rotate(-6deg);
  box-shadow: 0 8px 32px 0 rgba(162, 89, 236, 0.25), 0 3px 12px 0 rgba(106, 130, 251, 0.18);
  border-color: #a259ec;
}

.post-content-wrapper {
  flex: 1;
  min-width: 0;
}

.post-title {
  font-size: 18px;
  font-weight: bold;
  color: var(--primary-blue);
  margin: 0 0 8px 0;
  line-height: 1.4;
  transition: color 0.3s ease;
}

.post-item:hover .post-title {
  color: var(--primary-purple);
}

.post-content {
  color: var(--text-secondary);
  font-size: 15px;
  margin: 0 0 12px 0;
  line-height: 1.5;
}

.post-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  font-size: 13px;
  color: var(--text-muted);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background: var(--bg-primary);
  border-radius: var(--radius-sm);
  border: 1px solid var(--border-light);
  transition: all 0.3s ease;
}

.meta-item:hover {
  background: var(--light-blue);
  border-color: var(--primary-blue);
}

.meta-icon {
  font-size: 12px;
  color: var(--primary-blue);
}

/* 资源项目特殊样式 */
.resource-item .post-item-layout {
  align-items: stretch;
}

.resource-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-left: 16px;
  align-self: center;
}

.like-btn, .download-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s ease;
  border-radius: var(--radius-md);
}

.like-btn:hover, .download-btn:hover {
  transform: scale(1.05);
}

.like-btn.liked {
  background: var(--light-purple);
  border-color: var(--primary-purple);
  color: var(--primary-purple);
}

.download-icon {
  font-size: 14px;
  transition: transform 0.3s ease;
  color: var(--primary-blue);
}

.download-btn:hover .download-icon {
  transform: translateY(2px);
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  border: 2px dashed var(--border-medium);
  gap: 16px;
  animation: fadeIn 0.6s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.empty-icon {
  font-size: 48px;
  opacity: 0.6;
  animation: float 3s ease-in-out infinite;
  color: var(--text-muted);
}

.empty-text {
  font-size: 18px;
  color: var(--text-muted);
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .user-profile-layout {
    width: 95%;
    flex-direction: column;
  }
  
  .user-profile-main {
    margin-right: 0;
    margin-bottom: 20px;
  }
  
  .user-profile-info {
    position: static;
    max-width: none;
  }
}

@media (max-width: 768px) {
  .post-item-layout {
    flex-direction: column;
    gap: 12px;
  }
  
  .resource-actions {
    flex-direction: row;
    margin-left: 0;
    justify-content: center;
  }
  
  .profile-nick-row {
    flex-direction: column;
    gap: 8px;
  }
  
  .post-meta {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
